package com.ytclub.auth.application.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录上下文类
 *
 * @author: HuangQi
 * @date: Created in 23:07 2024/4/14
 * @description: 登录上下文
 */
public class LoginContextHolder {

    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL =
            new InheritableThreadLocal<>();

    /**
     * 设置登录上下文
     *
     * @param key 键
     * @param val 值
     */
    public static void set(String key, Object val) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, val);
    }

    /**
     * 获取登录上下文
     *
     * @param key 键
     * @return Object 值
     */
    public static Object get(String key) {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    /**
     * 获取登录id
     *
     * @return 登录id
     */
    public static String getLoginId() {
        return (String) getThreadLocalMap().get("loginId");
    }

    /**
     * 删除登录上下文
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * 获取ThreadLocalmap
     *
     * @return String map结合
     */
    public static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
